package cn.t222.ch04.pojo;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadLocalDemo implements Runnable{
    // SimpleDateFormat 不是线程安全的，所以每个线程都要有自己独立的副本
    private static final ThreadLocal<SimpleDateFormat>
            formatter = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMdd HHmm"));
    private volatile int count = 5;
    private AtomicInteger n = new AtomicInteger(5);
    private Vector<String> list = new Vector<>();
    public  int increment() {
        n.addAndGet(5);
       return n.getAndIncrement();
    }
    public static void main(String[] args) throws InterruptedException {
      /*  ThreadLocalDemo obj = new ThreadLocalDemo();
        for(int i=0 ; i<50; i++){
            Thread t = new Thread(obj, ""+i);
            Thread.sleep(new Random().nextInt(1000));
            t.start();
        }*/
        ExecutorService executorService = Executors.newFixedThreadPool(5);
//        Executors.newSingleThreadExecutor();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                5,
                10,
                1,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100),
                new ThreadPoolExecutor.CallerRunsPolicy());

        for(int i = 0; i <150; i++) {
            ThreadLocalDemo obj = new ThreadLocalDemo();
            executor.execute(obj);
        }
//        executor.awaitTermination(10,TimeUnit.SECONDS);
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }

    @Override
    public void run() {
        System.out.println("Thread Name= "+Thread.currentThread().getName()+" default Formatter = "+formatter.get().toPattern());
        try {
            if(count > 0) {
                count--;
                Thread.sleep(new Random().nextInt(1000));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //formatter pattern is changed here by thread, but it won't reflect to other threads
        formatter.set(new SimpleDateFormat());

        System.out.println("Thread Name= "+Thread.currentThread().getName()+" formatter = "+formatter.get().toPattern() + "===count:" + count);
    }
}
